<template>
  <el-card class="box-card" shadow="never">
    <div slot="header" class="clearfix">
      <span>我发起的流程</span>
    </div>
    <el-table :data="iInitiateProcessArray" size="mini" border stripe>
      <el-table-column label="序号" type="index" min-width="5%" header-align="center"></el-table-column>
      <el-table-column label="发起时间" prop="startTime" min-width="15%" header-align="center" :formatter="formatDate">
      </el-table-column>
      <el-table-column label="流程名称" prop="businessKey" min-width="20%" header-align="center"></el-table-column>
      <el-table-column label="当前节点" prop="currentTask" min-width="20%" header-align="center"></el-table-column>
      <el-table-column label="办理人" prop="assignee" min-width="20%" header-align="center"></el-table-column>
      <el-table-column min-width="20%" header-align="center">
        <template slot-scope="scope">
          <el-button type="text" size="mini"
                     @click="view(scope.row)">查看
          </el-button>
          <el-button type="text" size="mini"
                     @click="rollback(scope.row,scope.$index)">撤回
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="流程图" :visible.sync="dialogVisible" width="70%" :before-close="handleClose" :close-on-click-modal=false>
      <div ref="canvas" style="height: 20rem; width: 100%; margin: 0 auto"></div>
    </el-dialog>
  </el-card>
</template>

<script>
import BpmnModeler from "bpmn-js/lib/Modeler";
import "bpmn-js/dist/assets/diagram-js.css";
import "bpmn-js/dist/assets/bpmn-font/css/bpmn.css";
import "bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css";
import "bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css";
import moment from "moment";
export default {
  name: "IInitiateProcess",
  data() {
    return {
      iInitiateProcessArray: [],
      dialogVisible: false, // 控制对话框显示
      bpmnXML:'',
      historyData:''
    }
  },
  methods: {
    formatDate(row) {
      return moment(row.startTime).tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss');
    },
    rollback(row,index) {
      this.$confirm("确定要撤回？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http.post(`/instance/rollback/${row.processInstanceId}`).then((response) => {
          if (response.data.code == 1) {
            this.$message.success("流程撤回成功");
            this.iInitiateProcessArray.splice(index, 1);
          } else {
            this.$message.success("流程撤回失败");
          }
        })
      })
    },
    importXMLPromise(xmlData) {
      return new Promise((resolve, reject) => {
        this.bpmnModeler.importXML(xmlData, (err, warnings) => {
          if (err) {
            reject(err);
          } else {
            resolve(warnings);
          }
        });
      });
    },
    loadBPMN() {
      return this.importXMLPromise(this.bpmnXML).then(warnings => {
        this.bpmnModeler.get('canvas').zoom('fit-viewport');
        return warnings; // 可以返回 warnings 或其他有用的信息
      }).catch(error => {
        console.error('导入流程失败', error);
        this.$message.error('导入失败，请检查XML格式');
        throw error; // 重新抛出错误，以便可以在外部捕获
      });
    },
    applyColors() {
      const elementRegistry = this.bpmnModeler.get('elementRegistry');
      const modeling = this.bpmnModeler.get('modeling');
      // 定义颜色映射
      const colors = {
        waitingToDo: '#E6A23C',
        highPoint: '#E1F3D8',
        iDo: '#67C23A',
        highLine: '#D8E0D4'
      };
      // 遍历 historyData 并应用颜色
      Object.keys(this.historyData).forEach(key => {
        this.historyData[key].forEach(id => {
          if (id) {
            const element = elementRegistry.get(id);
            if (element) {
              // 判断元素类型，应用不同的样式
              if (element.type === 'bpmn:SequenceFlow') { // 对于连线
                modeling.setColor([element], {
                  stroke: colors[key]
                });
              } else { // 对于用户任务节点
                modeling.setColor([element], {
                  stroke: '#545454', // 边框颜色为黑色
                  fill: colors[key], // 填充颜色
                  color: colors[key] // 文本颜色
                });
              }
            }
          }
        });
      });
    },
    view(row) {
      this.dialogVisible = true;
      this.$nextTick(() => {
        if (!this.bpmnModeler) {
          this.bpmnModeler = new BpmnModeler({
            container: this.$refs.canvas,
            additionalModules: [
              {
                zoomScroll: ["value", ""],
                bendpoints: ["value", ""],
                paletteProvider: ["value", ""],
                contextPadProvider: ["value", ""],
                labelEditingProvider: ["value", ""]
              }
            ]
          });
        }
        // 加载数据
        const processInstanceId = row.id;
        this.$http.get(`/history/highLine/process/${processInstanceId}`).then((response) => {
          if (response.data.code == 1) {
            this.historyData = response.data.data;
          } else {
            console.log("获取流程实例历史数据失败");
          }
        });
        this.$http.get(`process/definitionXML/${processInstanceId}`).then(response => {
          if (response.data.code == 1) {
            this.bpmnXML = response.data.data;
            this.loadBPMN().then(() => {
              // 再次延迟，确保对话框完全渲染
              setTimeout(() => {
                this.applyColors();
              }, 50);
            });
          } else {
            this.$message.error("获取流程实例xml失败");
          }
        });
      });
    },
    // 关闭对话框
    handleClose() {
      this.dialogVisible = false;
      if (this.bpmnViewer) {
        this.bpmnViewer.destroy();
        this.bpmnViewer = null;
      }
    },
  },
  mounted() {
    this.$http.get("/instance/personal").then((response) => {
      if (response.data.code == 1) {
        this.iInitiateProcessArray = response.data.data
        console.log(this.iInitiateProcessArray)
      } else {
        console.log("获取创建流程实例数据失败")
      }
    })
  }
}
</script>

<style scoped>

</style>